package com.yc.txx.servlet;

import com.google.gson.Gson;
import com.yc.txx.biz.BizExcpetion;
import com.yc.txx.biz.LeaseBiz;
import com.yc.txx.entity.Lease;
import com.yc.txx.entity.User;
import com.yc.txx.vo.Result;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;

@WebServlet(name = "CommitServlet", value = "/CommitServlet.s")
public class CommitServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Result result;
        User myinfo = (User) request.getSession().getAttribute("myinfo");
        if(myinfo==null){
            result = Result.failure("请先登录系统!");
            final String json = new Gson().toJson(result);
            response.getWriter().append(json);
            return;
        }

        final String cid = request.getParameter("cid");
        final String days = request.getParameter("days");
        final String money = request.getParameter("money");

        Lease lease = new Lease();
        lease.setCid(Integer.parseInt(cid));
        lease.setDays(days);
        lease.setMoney(new BigDecimal(money));
        final String[] times = days.split("\\D+");
        // 构建提车时间
        lease.setBeginday(LocalDate.of(Integer.parseInt(times[0]),
                Integer.parseInt(times[1]),
                Integer.parseInt(times[2])));

        // 默认值
        lease.setUid(myinfo.getId());
        lease.setState("支付");  // TODO 沙箱支付

        LeaseBiz leaseBiz = new LeaseBiz();
        try {
            leaseBiz.commit(lease);
            result = Result.success("订单提交成功!");
        } catch (BizExcpetion bizExcpetion) {
            bizExcpetion.printStackTrace();
            result = Result.failure(bizExcpetion.getMessage());
        }

        final String json = new Gson().toJson(result);
        response.getWriter().append(json);
    }
}
